package website.lucaswork.survey.core.dtos;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import website.lucaswork.survey.core.entities.Authority;
import website.lucaswork.survey.core.entities.Survey;
import website.lucaswork.survey.core.entities.User;
import website.lucaswork.survey.core.enums.RoleEnum;
import website.lucaswork.survey.core.utils.DefaultValues;

import java.time.LocalDate;
import java.time.ZoneId;

@Component
public class DtoFactory {
	@Autowired
	private DefaultValues defaultValues;
	
	public SurveySummaryDTO produceSurveySummaryDTO(Survey survey) {
		SurveySummaryDTO ret = new SurveySummaryDTO();
		ret.setId(survey.getId());
		ret.setTitle(survey.getTitle());
		if (survey.getCover() == null) {
			ret.setCover(defaultValues.getDefaultCoverUrl());
		} else {
			ret.setCover(survey.getCover());
		}
		ret.setSlug(survey.getSlug());
		ret.setIntro(survey.getDescription());
		return ret;
	}

	public UserDTO produceUserSummaryDTO(User user) {
		UserDTO ret = new UserDTO();
		ret.setUsername(user.getUsername());
		ret.setEmail(user.getEmail());
		ret.setRegisterTime(user.getCreatedAt().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
		boolean isAdmin = false;
		for (Authority authority : user.getAuthorities()) {
		    if (RoleEnum.ROLE_ADMIN.equals(authority.getRole())) {
		        isAdmin = true;
		        break;
            }
        }
        ret.setAdmin(isAdmin);
		ret.setActive(User.UserStatus.STATUS_ACTIVE.equals(user.getStatus()));
		return ret;
	}
}
